<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <el-button type="primary" size="medium" icon="el-icon-plus" @click="addTradeMark">
          添加
        </el-button>
      </div>

      <el-table :data="trademarkList" border style="width: 100%">
        <el-table-column prop="id" label="序号" width="180"> </el-table-column>
        <el-table-column prop="tmName" label="品牌名称" width="180">
        </el-table-column>
        <el-table-column prop="logoUrl" label="品牌LOGO">
          <template slot-scope="scope">
            <img :src="scope.row.logoUrl" style="width: 80px;height: 80px;" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="medium"
              type="warning"
              @click="handleEdit(scope.$index, scope.row)"
              icon="el-icon-edit"
              >编辑
            </el-button>
            <el-button
              size="medium"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[3, 6, 9]"
        :page-size="limit"
        layout="prev, pager, next, jumper,->,total, sizes"
        :total="total"
      >
      </el-pagination>
      <!-- 弹框 -->
      <el-dialog
        :title="tmForm.id ? '修改品牌' : '添加品牌'"
        :visible.sync="dialogFormVisible"
      >
        <el-form :model="tmForm" label-width="120px" ref="tmForm" :rules="rules">
          <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
            <el-input v-model="tmForm.tmName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="品牌LOGO" :label-width="formLabelWidth" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              :action="action"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div class="el-upload__tip" slot="tip">
                上传图片必须是jpg且不能大于2M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelSave('tmForm')">取 消</el-button>
          <el-button type="primary" @click="onSave('tmForm')">保 存</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import trademarkApi from "@/api/product/trademark";
import { Message } from "element-ui";
import { cloneDeep } from "lodash";
export default {
  name: "trademark",
  data() {
    return {
      page: 1,
      limit: 3,
      total: 0,
      trademarkList: [],
      dialogFormVisible: false,
      tmForm: {
        // id: "",
        tmName: "",
        logoUrl: "",
      },
      formLabelWidth: "120px",
      action: `${process.env.VUE_APP_BASE_API}/admin/product/upload`,
      // 添加/修改品牌的校验规则
      rules:{
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 10, message: '名称长度为2到10个字符', trigger: 'blur' },
        ],
        logoUrl: [
          { required: true, message: '请输入上传图片', trigger: 'change' },
        ]
      }
    };
  },
  watch: {},
  mounted() {
    this.getList();
  },
  methods: {
    // 初始表单内容
    initForm() {
      this.tmForm.tmName = "";
      this.tmForm.logoUrl = "";
    },
    // 点击添加的回调
    addTradeMark() {
      this.dialogFormVisible = true;
    },
    // 点击保存的回调
    onSave(formName){
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          try {
            if (this.tmForm.id) {
              await trademarkApi.update(this.tmForm);
              Message.success('编辑成功')
            } else {
              await trademarkApi.save(this.tmForm);
              Message.success('添加成功')
            }
            this.getList()
            //隐藏弹框
            this.dialogFormVisible = false;
            //重置表单
            this.initForm()
          } catch (error) {
            Message.error('保存失败')
            console.error(error)
            this.dialogFormVisible = false
          }
        } else {
          return false;
        }
      });
    },
    
    // 点击取消的回调
    cancelSave(formName) {
      this.$refs[formName].resetFields();
      this.dialogFormVisible = false;
      this.initForm();
    },
    // 点击编辑的回调
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.tmForm = cloneDeep(row);
    },
    // 点击删除的回调
    handleDelete(index, row) {
      this.$confirm(`确定要删除${row.tmName}吗`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await trademarkApi.delete(row.id);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          // 刷新页面
          this.getList(this.trademarkList.length===1 ? this.page-1 : this.page)
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 获取列表数据
    async getList() {
      try {
        let result = await trademarkApi.getPage(this.page, this.limit);
        this.trademarkList = result.data.records;// 拿到展示的数据
        this.total = result.data.total;//拿到总条数
      } catch (error) {
        console.log(error);
        Message.error("获取品牌列表失败");
      }
    },
    // 每页条数改变的回调
    handleSizeChange(val) {
      this.limit = val;
      this.getList();
    },
    // 翻页的回调
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },

    // 图片上传成功的回调
    handleAvatarSuccess(res, file) {
      this.tmForm.logoUrl = res.data;
    },
    // 图片上传之前校验的回调
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
